﻿using System;
using System.Threading;
using System.Threading.Tasks;
using K9Nano.Caching;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.Share;

namespace K9Nano.Caching
{
    public class DefaultSharedTenantCache : ISharedTenantCache, IScopedDependency
    {
        protected readonly ITypedCache<SharedTenantCacheItem> Cache;
        protected readonly IReadOnlyRepository ReadOnlyRepository;

        public DefaultSharedTenantCache(IReadOnlyRepository readOnlyRepository, ITypedCache<SharedTenantCacheItem> cache)
        {
            ReadOnlyRepository = readOnlyRepository;
            Cache = cache;
        }
        
        public SharedTenantCacheItem Get(Guid id)
        {
            return Cache.GetOrAdd(id.ToString(), _ => GetTenant(id));
        }

        protected virtual SharedTenantCacheItem GetTenant(Guid id)
        {
            var item = ReadOnlyRepository.QueryFirstOrDefault<SharedTenantCacheItem>(
                $"select Id, TenancyName, DisplayName, EditionId from {K9SharedConstants.SharedSchemePlaceholder}.app_tenant where Id=@id",
                new { id = id.ToString() });
            return item;
        }
    }
}